import React, { useState, useEffect, useLayoutEffect } from 'react';
import { Button, View, Text, FlatList, Image, StyleSheet, SafeAreaView, Pressable, ScrollView, ImageBackground } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Icon1 from 'react-native-vector-icons/AntDesign';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

function Myxyq({ navigation }) {
    // const navigation = useNavigation();
    const [refreshing, isRefresh] = useState(true);
    const [isCommentInputVisible, setIsCommentInputVisible] = useState(false);
    const [userInfo, setUserInfo] = useState({});
    const [comments, setComments] = useState([]);
    const [commentIndex, setCommentIndex] = useState(null);
    const [currentPostIndex, setCurrentPostIndex] = useState(0);
    const [apiResponse, setApiResponse] = useState(null);
    const [postID, setPostID] = useState(null);
    const [time, setTime] = useState('');
    const [likes, setLikes] = useState([]);
    const [liked, setLiked] = useState([]);
    const [view, setView] = useState([]);
    const [mark, setMarked] = useState([]);
    const [hotPosts, setHotPosts] = useState([]);
    const handleDeletePost = (index) => {
        axios.post('http://47.111.227.58:3000/dynamic/deleteUserDynamic', {
            id: index
        })
            .then(res => {
                console.log(res.data);
                getDynamicList()
            })
            .catch(error => {
                console.error(error);
            });
    }
    const getHotPost = () => {
        axios.get('http://47.111.227.58:3000/dynamic/getDynamicView')
            .then(res => {
                // console.log(res.data);
                setHotPosts(res.data.results);
            })
            .catch(error => {
                console.error(error);
            });
    }
    const getDynamicList = () => {
        axios.get('http://47.111.227.58:3000/dynamic/getdynamicByUser',{
            params: {
                username: userInfo.username
            }
        }).then(res => {
            // console.log(res.data);
            setApiResponse(res.data.results)
            const initialLikes = res.data.results.map(item => item.likes);
            setLikes(initialLikes);
            const initialLiked = res.data.results.map(item => item.likedUsers?.split(',').includes(userInfo.username));
            setLiked(initialLiked);
            const initialView = res.data.results.map(item => item.view);
            setView(initialView)
            const initialComments = res.data.results.map(item => item.comments);
            setComments(initialComments);
            const initialMarked = res.data.results.map(item => item.markUsers?.split(',').includes(userInfo.username));
            setMarked(initialMarked);
            isRefresh(false);
        })
    }
    const handleRefresh = () => {
        isRefresh(true);
        getDynamicList();
    }
    const handleLike = (index) => {
        console.log(liked)
        if (liked[index]) {
            // 如果用户已经点过赞，那么再次点击就取消点赞
            let newLikes = [...likes];
            newLikes[index] = Number(newLikes[index]) - 1;
            setLikes(newLikes);
            let newLiked = [...liked];
            newLiked[index] = false;
            setLiked(newLiked);
            axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
                data: {
                    id: apiResponse[index].id,
                    likes: newLikes[index]
                }
            }).then(res => {
                console.log(res.data);
                // 更新点赞用户列表
                axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
                    postId: apiResponse[index].id,
                    userId: userInfo.username
                }).then(res => {
                    console.log(res.data);
                });
            });
        } else {
            // 如果用户还没点过赞，那么点击就增加点赞
            let newLikes = [...likes];
            newLikes[index] = Number(newLikes[index]) + 1;
            setLikes(newLikes);
            let newLiked = [...liked];
            newLiked[index] = true;
            setLiked(newLiked);
            axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
                data: {
                    id: apiResponse[index].id,
                    likes: newLikes[index]
                }
            }).then(res => {
                console.log(res.data);
                // 更新点赞用户列表
                axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
                    postId: apiResponse[index].id,
                    userId: userInfo.username
                }).then(res => {
                    console.log(res.data);
                });
            });
        }
    };
    const handleMarked = (index) => {
        if (mark[index]) {
            let newMarked = [...mark];
            newMarked[index] = false;
            setMarked(newMarked);
            axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
                postId: apiResponse[index].id,
                userId: userInfo.username
            }).then(res => {
                console.log(res.data);
            });
        } else {
            let newMarked = [...mark];
            newMarked[index] = true;
            setMarked(newMarked);
            axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
                postId: apiResponse[index].id,
                userId: userInfo.username
            }).then(res => {
                console.log(res.data);
            });
        }
    };
    const handlePostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...view];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: apiResponse[index].id,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };


    useEffect(() => {
        (async () => {
            isRefresh(true);
            // getDynamicList()
            const currentTime = getFormattedCurrentTime();
            setTime(currentTime)
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo))
            }
        })();
    }, []);
    useEffect(() => {
        if (userInfo.username) {
            getDynamicList();
            getHotPost()
        }
    }, [userInfo]);
    const handleHideCommentInput = () => {
        if (isCommentInputVisible) {
            setIsCommentInputVisible(false);
        }
    };
    const getFormattedCurrentTime = () => {
        const now = new Date(); // 获取当前时间
        const year = now.getFullYear(); // 年
        const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月，月份是从0开始计数的
        const day = now.getDate().toString().padStart(2, '0'); // 日
        const hours = now.getHours().toString().padStart(2, '0'); // 时
        const minutes = now.getMinutes().toString().padStart(2, '0'); // 分
        const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    const onCommentSubmit = (comment) => {
        console.log('评论提交：', comment);
        // console.log(userInfo)
        const currentTime = getFormattedCurrentTime();
        setTime(currentTime)

        if (comment != '') {
            axios.post('http://47.111.227.58:3000/dynamic/addcomments', {
                data: {
                    dy_id: postID,
                    username: userInfo.username,
                    phone: userInfo.phone,
                    userImg: userInfo.imgUrl,
                    content: comment,
                    uploadTime: time
                }
            }).then(res => {
                console.log(res.data)
                let newComment = [...comments];
                newComment[commentIndex] = Number(newComment[commentIndex]) + 1;
                setComments(newComment);
                axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicComments', {
                    data: {
                        id: postID,
                        comment: newComment[commentIndex]
                    }
                }).then(res => {
                    console.log(res.data);
                });
            })
        }
        setIsCommentInputVisible(false);
    }
    useLayoutEffect(() => {
        navigation.setOptions({
            headerShown: false, // 显示头部

        });
    }, [navigation]);
    const renderItem = ({ item, index }) => {
        return (
            <Pressable onPress={() => handlePostClick(item.id, index)}>
                <View style={styles.messageItem}>
                    <View style={styles.messageHeader}>
                        <Image style={styles.avatar} source={{ uri: item.userImg }} />
                        <Text style={styles.username}>{item.username}</Text>
                        <Text style={styles.uploadTime}>{item.uploadTime}</Text>
                    </View>
                    <Text style={styles.messageText}>{item.desc}</Text>
                    {item.imgUrl && (
                        <Image style={styles.messageImage} source={{ uri: item.imgUrl }} />
                    )}
                    <Text style={styles.boardText}>#{item.board}</Text>
                    <View style={styles.interactionBar}>
                        <View style={styles.leftInteractions}>
                            <Pressable style={styles.interactionButton} onPress={() => handleMarked(index)}>
                                <Icon1 name={mark[index] ? 'tags' : 'tagso'} size={18} color={mark[index] ? '#5D81D0' : '#777777'} style={{ marginRight: 5 }} />
                                <Text style={{ color: mark[index] ? '#5D81D0' : '#777777' }}>{mark[index] ? '弃坑' : '马住'}</Text>
                            </Pressable>
                            <Pressable style={styles.interactionButton}>
                                <Icon name="certificate" size={18} color="#b8b8b8" style={{ marginRight: 5 }} />
                                <Text>赞赏</Text>
                            </Pressable>
                            <Pressable style={styles.interactionButton} onPress={() => handleLike(index)}>
                                <Icon name={liked[index] ? 'thumbs-up' : 'thumbs-o-up'} size={18} color={liked[index] ? '#FE4F37' : '#777777'} style={{ marginRight: 5 }} />
                                <Text style={{ color: liked[index] ? '#FE4F37' : '#777777' }}>{likes[index] > 0 ? likes[index] : '点赞'}</Text>
                            </Pressable>
                        </View>
                        <View style={styles.rightInteractions}>
                            <Pressable
                                style={styles.rightInteraction}
                                onPress={() => { setCommentIndex(index); setPostID(item.id); setIsCommentInputVisible(true) }}
                            >
                                <Icon name="pencil-square-o" size={18} color="#b8b8b8" style={{ marginRight: 5, marginLeft: 5 }} />
                                <Text style={{ marginRight: 5 }}>{comments[index] > 0 ? comments[index] : '评论'}</Text>
                            </Pressable>
                            {item.username === userInfo.username && (
                                <Pressable onPress={() => handleDeletePost(item.id)} style={styles.rightInteraction1}>
                                    <Text>删除</Text>
                                </Pressable>
                            )}
                        </View>
                    </View>
                </View>
            </Pressable>
        );
    };

    return (
        <ScrollView>
            <View style={styles.container}>
                <ImageBackground
                    source={{ uri: userInfo.imgUrl }}
                    style={styles.headerBackground}
                    blurRadius={30}
                >
                    <View style={styles.profileInfo}>
                        <Image style={styles.avatar} source={{ uri: userInfo.imgUrl }} />
                        <View style={styles.info}>
                            <Text style={styles.id}>ID:{userInfo.id}</Text>
                            <Text style={styles.name}>{userInfo.username}</Text>
                        </View>
                    </View>
                    <View style={styles.statsfm}>
                        <Image style={styles.iswomenorman} source={require('../assets/women.png')} />
                    </View>
                    <Pressable onPress={() => navigation.navigate('个人信息')}>
                        <View style={styles.statsRow}>
                            <Text style={styles.statLabel}>设置个人信息</Text>
                        </View>
                    </Pressable>
                </ImageBackground>
                <View style={styles.menu}>
                    <Text style={styles.menuText1}>历史发帖</Text>
                    <Image style={styles.Icon} source={require('../assets/set.png')} />
                    <Text style={styles.menuText2}>权限设置</Text>
                </View>
                <FlatList
                    data={apiResponse}
                    renderItem={renderItem}
                    keyExtractor={item => item.id}
                    refreshing={refreshing}
                    onRefresh={handleRefresh}
                />
            </View>
        </ScrollView >
    );
}

const styles = StyleSheet.create({
    headerTitle: {
        color: '#fff', // 标题颜色
        fontSize: 20, // 标题字体大小
        fontWeight: 'bold',
    },
    statsRow: {
        borderWidth: 0.5, // 设置边框宽度
        borderColor: '#E8E8E8', // 设置边框颜色，您可以根据需要更改颜色
        backgroundColor: 'transparent', // 设置背景颜色为透明
        margin: 10, // 设置外边距
        marginLeft: 20, // 设置左边距
        marginRight: 20, // 设置右边距
        padding: 10, // 设置内边距
        borderRadius: 20, // 设置圆角边框
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',

    },
    profileInfo: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        marginTop: 40,
        marginLeft: 20,

    },
    info: {
        marginLeft: 15,
        marginTop: 80,
        flexDirection: 'column',
    },
    statLabel: {
        fontSize: 15,
        fontWeight: 'bold',

        color: '#696969',
    },
    container: {
        flex: 1,
        backgroundColor: '#f0f0f0',//#f0f0f0
    },
    headerBackground: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: 300,

    },
    id: {//ID
        fontSize: 13,
        marginLeft: 15,
        color: '#CFCFCF',
    },
    name: {
        fontSize: 20,
        color: '#ffffff',
        marginLeft: 15,
        fontWeight: 'bold',
    },
    iswomenorman: {
        marginLeft: 20,
        width: 20,
        height: 20,

    },
    menu: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginTop: 300,
    },
    Icon: {
        height: 2,
        width: 2,
        marginRight: 40,
        color: '#000',
    },
    menuText1: {

        fontSize: 15,
        fontWeight: 'bold',
        color: '#000',
        marginLeft: 2,
        marginTop: 5,
    },
    menuText2: {
        fontSize: 15,
        fontWeight: 'normal',
        color: '#828282',
        marginRight: 2,
        marginTop: 5,
    },
    menuItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#EFEFEF',
    },
    lastItem: {
        borderBottomWidth: 0, // 移除底部边框
    },
    menuIcon: {
        width: 20,
        height: 20,
        marginRight: 10,
    },
    menuText: {
        flex: 1,
        fontSize: 16,
        // ... 根据图片调整样式 ...
    },
    arrowIcon: {
        width: 16,
        height: 16,
    },
    avatar: {
        width: 40,
        height: 40,
        borderRadius: 20,
        marginRight: 10,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    messageItem: {
        backgroundColor: '#fff',
        padding: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        marginBottom: 10,
        paddingLeft: 15,
    },
    messageHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 5,
    },
    avatar: {
        width: 40,
        height: 40,
        borderRadius: 20,
        marginRight: 10,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    messageImage: {
        width: '70%',
        height: 170,
        borderRadius: 5,
        marginBottom: 5,
        borderWidth: 1,
        borderColor: '#ddd',
        marginBottom: 10,
    },
    username: {
        fontWeight: 'bold',
    },
    uploadTime: {
        // fontWeight: 'bold',
        color: '#b8b8b8',
        fontSize: 12,
        marginLeft: 'auto',
        marginRight: 5,
    },
    messageText: {
        marginBottom: 5,
    },
    boardText: {
        height: 25,
        width: 60,
        backgroundColor: '#DDE1EA',
        color: '#576B94',
        marginBottom: 5,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 12,
        // fontWeight: 'bold',
    },
    interactionBar: {
        flexDirection: 'row',
        justifyContent: 'space-between', // 确保内容分布在两侧
        alignItems: 'center', // 垂直居中
    },
    leftInteractions: {
        flexDirection: 'row', // 使得按钮水平排列
    },
    rightInteractions: {
        flexDirection: 'row', // 使得按钮水平排列
    },
    rightInteraction: {
        flexDirection: 'row',
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 20,
        padding: 5,
    },
    rightInteraction1: {
        flexDirection: 'row',
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 20,
        padding: 5,
        marginLeft: 2,
    },
    interactionButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingRight: 15,
    },
    commentButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 10,
        paddingRight: 10,
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 20,
        padding: 5,
    },
    commentInput: {
        borderColor: '#ccc',
    },
});

export default Myxyq;
